<?php
/**
 * Created by PhpStorm.
 * User: iamya
 * Date: 2017/10/10
 * Time: 8:48
 */

namespace app\circle\controller;


use app\circle\model\BaseModel;
use app\circle\model\CircleMemberModel;
use app\circle\model\CircleModel;
use app\circle\model\CompanyModel;
use app\circle\model\MemberAttentionModel;
use app\circle\model\MemberModel;
use app\circle\model\ThemeModel;
use app\common\model\UserModel;
use org\util\HelpUtil;
use think\Controller;
use think\Cookie;
use think\Request;
use think\Session;
use think\Validate;

class PublicController extends BaseController
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    /**
     * 登陆
     * @return mixed
     */
    public function userLogin()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $model = new MemberModel();
            if ($model->login($data['member_mobile'], $data['member_pass'])) {
                $url = $this->request->param('reback');
                $this->success('登陆成功', $url);
            } else {
                $this->error($model->getError());
            }
        }
        $reback = $this->request->param('reback', url('Meeting/index'));
        $this->assign('reback', $reback);
        return $this->fetch();
    }

    public function userLoginOut()
    {
        $reback = $this->request->param('reback', '');
        Cookie::set('circleMemberDes', null);
        $this->success('退出成功', empty($reback) ? url('userLogin') : $reback);
    }

    /**
     * 注册
     * @return mixed
     */
    public function userReg()
    {
        if ($this->request->post()) {
            $data = $this->request->param();
            $model = new MemberModel();
            $validate = new Validate([
                ['member_pass', 'require', '请输入密码'],
                ['member_pass_ng', 'require|confirm:member_pass', '请输入确认密码|两次密码输入不一样'],
                ['member_mobile', 'unique:circle_member', '该手机号已经注册'],
                ['company_name', 'require', '请填写企业名称'],
                ['member_duties', 'require', '请填写在公司内的职务']
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $data['member_tel'] = $data['member_mobile'];
            $smsValid = session('sms_valid');
            if ($smsValid[1] < time() - 3 * 60) {
                session('sms_valid', null);
                $this->error('短信验证码已失效!');
            } else if ($smsValid[0] != $data['vcode']) {
                $this->error('短信验证码错误');
            }
            $companyModel = new CompanyModel();
            $companyInfo = $companyModel->where('company_name', $data['company_name'])->find();
            if (empty($companyInfo)) {
                $companyInfo = [
                    'company_name' => $data['company_name'],
                    'is_examine' => 0
                ];
                $companyModel->addData($companyInfo);
                $companyInfo['company_id'] = $companyModel->getLastInsID();
            }
            $data += [
                'company_id' => $companyInfo['company_id'],
                'company_name' => $companyInfo['company_name']
            ];
            if ($model->addData($data)) {
                $model->login($data['member_mobile'], $data['member_pass']);
                $url = $this->request->param('reback', url('Theme/index'));
                $this->success('注册成功', $url);
            } else {
                $this->error($model->getError());
            }
        }
        $reback = $this->request->param('reback', url('Meeting/index'));
        $this->assign('reback', $reback);
        return $this->fetch();
    }

    /**
     * 发送短信
     */
    public function sendSms()
    {
        $mobile = $this->request->param('mobile');
        $userModel = new UserModel();
        if ($userModel->isMobile($mobile) === false) {
            $this->error('手机号格式有误！');
        }
        $randNum = HelpUtil::randString(6, 1);
        $randNum = 888999;
        $data = [$randNum, 3];
        //send_sms($mobile, $data, '149180');
        session('sms_valid', [$randNum, time()]);
        $this->success('短信发送成功!');
    }

    /**
     * 检查手机号是否已经注册
     */
    public function isReg()
    {
        $mobile = $this->request->param('member_mobile');
        $model = new MemberModel();
        $count = $model->where('member_mobile', $mobile)->count();
        if ($count) {
            $this->error('该手机号已经注册');
        } else {
            $this->success('改手机号可以注册');
        }
    }

    /**
     * 检查企业名称是否已经在企业库内
     */
    public function isCompany()
    {
        $companyName = $this->request->param('company_name', '');
        $model = new CompanyModel();
        if ($model->where('company_name', $companyName)->count()) {
            $this->success('该企业已经注册');
        } else {
            $this->error('该企业尚未注册');
        }
    }

    /**
     * 用户名片
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     */
    public function memberCard()
    {
        // 创建SDK实例
        $script = &load_wechat('Script', $this->getWxconfig());
        // 获取JsApi使用签名，通常这里只需要传 $ur l参数
        $options = $script->getJsSign(get_current_url());
        $this->assign('options', $options);
        $memberId = $this->request->param('member_id', 0);
        $circleMemberDes = cookie('circleMemberDes');
        $regMemberId = 0;
        if (!empty($circleMemberDes)) {
            $info = str_decode($circleMemberDes);
            if (!empty($info)) {
                $info = explode(config('base.login_token'), $info);
                if (count($info) == 2) {
                    $regMemberId = $info[0];
                }
            }
        }
        $model = new MemberModel();
        $isAttention = 0;
        $memberInfo = $model->where('member_id', $memberId)->find();
        if ($regMemberId) {
            $attemtionModel = new MemberAttentionModel();
            $isAttention = $attemtionModel->where(['member_id' => $regMemberId, 'attention_member_id' => $memberId])->count();
        }
        $memberInfo['is_attention'] = $isAttention;
        if ($this->request->isAjax()) {
            $memberInfo['company_info'] = $memberInfo->company_info;
            $memberInfo['theme_list'] = $memberInfo->theme_list;
            return $memberInfo;
        }

        $this->assign('isLogin', $regMemberId);
        $this->assign('userInfo', $memberInfo);
        return $this->fetch();
    }

    public function circleShare()
    {
        // 创建SDK实例
        $script = &load_wechat('Script', $this->getWxconfig());
        // 获取JsApi使用签名，通常这里只需要传 $ur l参数
        $options = $script->getJsSign(get_current_url());
        $this->assign('options', $options);
        $circleId = $this->request->param('circle_id', 0);
        $circleModel = new CircleModel();
        $circleInfo = $circleModel->where('circle_id', $circleId)->find();
        $themeModel = new ThemeModel();
        $circleInfo['theme_list'] = $themeModel->where('circle_id', $circleId)->limit(5)->order('create_time desc')->select();
        $memberModel = new CircleMemberModel();
        $isJoin = 0;
        $memberId = $this->getMemberId();
        $cmState=$memberModel->where(['member_id'=>$memberId,'circle_id'=>$circleId])->find();
        $this->assign('circle_member_info',$cmState);
        if ($memberId > 0) {
            if ($cmState['cm_state']=2||empty($cmState)) {
                    $isJoin=1;
            }else if ($cmState['cm_state']=1){
                $isJoin = 2;
            } else {
                $isJoin = 3;
            };
        }
        $this->assign('is_join', $isJoin);
        $circleInfo['member_list'] = $memberModel->where(['circle_id'=>$circleId,'cm_state'=>1])->limit(6)->order('member_id desc')->select();
        $this->assign('circleInfo', $circleInfo);
        return $this->fetch();
    }

    public function circleApply()
    {
        $memberId = $this->getMemberId();
        if (!$memberId) {
            $this->error('请先登陆');
        }
        $circleId = $this->request->param('circle_id', 0);
        $circleInfo=[];
        if (empty($circleId)) {
            $this->error('请指定圈子');
        }else{
            $circleModel = new CircleModel();
            $circleInfo = $circleModel->where('circle_id', $circleId)->find();
            $this->assign('circle_info',$circleInfo);
        }
        $circleMemberModel=new CircleMemberModel();
        $cmState=$circleMemberModel->where(['member_id'=>$memberId,'circle_id'=>$circleId])->find();
        $this->assign('circle_member_info',$cmState);
        if (!empty($cmState)&&$cmState['cm_state']==0){
            $this->error('该用户已申请此圈子');
        }elseif ($cmState['cm_state']==1){
            $this->error('该用户已加入此圈子');
        }
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $validate = new Validate([
                ['circle_id', 'require', '请指定圈子'],
                ['cm_applycontent', 'require', '请填写申请信息']
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $memberModel = new MemberModel();
            $memberInfo = $memberModel->where('member_id', $memberId)->find();
            $data = [
                'member_id' => $memberInfo['member_id'],
                'member_name' => $memberInfo['member_name'],
                'circle_id'=>$circleInfo['circle_id'],
                'circle_name'=>$circleInfo['circle_name'],
                'cm_applycontent'=>$data['cm_applycontent'],
                'cm_applytime'=>time(),
                'cm_state'=>0,
                'cm_jointime'=>0,
                'is_identity'=>2,
                'cm_thcount'=>0,
                'cm_comcount'=>0,
                'is_recommend'=>0
            ];
            if (empty($cmState)){
                if ($circleMemberModel->addData($data)){
                    $this->success('申请成功,请等待管理员处理');
                }
            }else{
                $data['id']=$cmState['id'];
                if ($circleMemberModel->editData($data)){
                    $this->success('重新申请成功,请等待管理员处理');
                }
            }
            $this->error('网络错误请稍后重试');
        }
        return $this->fetch();
    }
}